package com.fengba.nanzhi.myfengba;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.login.Login;
import com.fengba.nanzhi.tabbar01.MultiChooseActivity;
import com.fengba.nanzhi.utils.FX_SignInUtil;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MyCF extends Activity implements View.OnClickListener {


    private RecyclerView mCardyhk;
    private JSONArray jsonArray1;
    private View view1;
    private View view2;

    private String type;

    private TextView shdztitle;

    private RecyclerView nCardyhk;
    private JSONArray jsonArray2;
    private ViewPager viewPager;
    private ArrayList<View> pageview;
    private TextView videoLayout;
    private TextView musicLayout;
    // 滚动条图片
    private ImageView scrollbar;
    // 滚动条初始偏移量
    private int offset = 0;
    // 当前页编号
    private int currIndex = 0;
    // 滚动条宽度
    private int bmpW;
    //一倍滚动量
    private int one;

    public MyCF() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fx_my_cf);

        Bundle bundle = getIntent().getExtras();
        type=(String)bundle.getSerializable("type");
        shdztitle=findViewById(R.id.shdztitle);
        if (type.equals("0"))
        {
            shdztitle.setText("我的拼手气");
            TextView videoLayout=findViewById(R.id.videoLayout);
            videoLayout.setText("中疯付款记录");
        }else
        {
            shdztitle.setText("我的抽疯");
        }

        /**
         * 返回
         */
        ImageButton Mcfbtn01 = (ImageButton) findViewById(R.id.Mcfbtn01);
        Mcfbtn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        //查找布局文件用LayoutInflater.inflate
        LayoutInflater inflater = getLayoutInflater();
        //左边
        view1 = inflater.inflate(R.layout.fx_cf_all, null);
        final RefreshLayout refreshLayout = (RefreshLayout) view1.findViewById(R.id.ArefreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {


            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        init();
                        if (jsonArray1 == null) {
                            Toast.makeText(MyCF.this, "已经没有更多数据了", Toast.LENGTH_SHORT).show();
                            refreshLayout.finishRefresh();
                        } else {
                            Toast.makeText(MyCF.this, "查询成功", Toast.LENGTH_SHORT).show();
                            refreshLayout.finishRefresh();
                        }
                        /**
                         * 刷新完成后调用此方法，要不然刷新效果不消失
                         */

                    }
                }, 0);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });


        //右边
        view2 = inflater.inflate(R.layout.fx_cf_winn, null);
        final RefreshLayout refreshLayouts = (RefreshLayout) view2.findViewById(R.id.WrefreshLayout);
        refreshLayouts.setOnRefreshListener(new OnRefreshListener() {

            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (jsonArray2 == null) {
                            Toast.makeText(MyCF.this, "已经没有更多数据了", Toast.LENGTH_SHORT).show();
                            refreshLayouts.finishRefresh();
                        } else {
                            init2();
                            Toast.makeText(MyCF.this, "查询成功", Toast.LENGTH_SHORT).show();
                            refreshLayouts.finishRefresh();
                        }
                        /**
                         * 刷新完成后调用此方法，要不然刷新效果不消失
                         */

                    }
                }, 0);
            }
        });
        refreshLayouts.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        init();
        init2();
        videoLayout = (TextView) findViewById(R.id.videoLayout);
        musicLayout = (TextView) findViewById(R.id.musicLayout);
        scrollbar = (ImageView) findViewById(R.id.scrollbar);
        videoLayout.setOnClickListener(this);
        musicLayout.setOnClickListener(this);
        pageview = new ArrayList<View>();
        //添加想要切换的界面
        pageview.add(view1);
        pageview.add(view2);
        //数据适配器
        PagerAdapter mPagerAdapter = new PagerAdapter() {


            @Override
            //获取当前窗体界面数
            public int getCount() {
                // TODO Auto-generated method stub
                return pageview.size();
            }

            @Override
            //判断是否由对象生成界面
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            //使从ViewGroup中移出当前View
            public void destroyItem(View arg0, int arg1, Object arg2) {
                ((ViewPager) arg0).removeView(pageview.get(arg1));
            }

            //返回一个对象，这个对象表明了PagerAdapter适配器选择哪个对象放在当前的ViewPager中
            public Object instantiateItem(View arg0, int arg1) {
                ((ViewPager) arg0).addView(pageview.get(arg1));
                return pageview.get(arg1);
            }
        };
        //绑定适配器
        viewPager.setAdapter(mPagerAdapter);
        //设置viewPager的初始界面为第一个界面
        viewPager.setCurrentItem(0);
        //添加切换界面的监听器
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        // 获取滚动条的宽度
        bmpW = 22;
        //为了获取屏幕宽度，新建一个DisplayMetrics对象
        DisplayMetrics displayMetrics = new DisplayMetrics();
        //将当前窗口的一些信息放在DisplayMetrics类中
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        //得到屏幕的宽度
        int screenW = displayMetrics.widthPixels;
        //计算出滚动条初始的偏移量
        offset = 0-bmpW;
        //计算出切换一个界面时，滚动条的位移量
        one = (screenW / 2);
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        //将滚动条的初始位置设置成与左边界间隔一个offset
        scrollbar.setImageMatrix(matrix);

    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageSelected(int arg0) {
            Animation animation = null;
            switch (arg0) {
                case 0:
                    /**
                     * TranslateAnimation的四个属性分别为
                     * float fromXDelta 动画开始的点离当前View X坐标上的差值
                     * float toXDelta 动画结束的点离当前View X坐标上的差值
                     * float fromYDelta 动画开始的点离当前View Y坐标上的差值
                     * float toYDelta 动画开始的点离当前View Y坐标上的差值
                     **/
                    animation = new TranslateAnimation(one, 0, 0, 0);
                    break;
                case 1:
                    animation = new TranslateAnimation(offset, one, 0, 0);
                    break;
            }
            //arg0为切换到的页的编码
            currIndex = arg0;
            // 将此属性设置为true可以使得图片停在动画结束时的位置
            animation.setFillAfter(true);
            //动画持续时间，单位为毫秒
            animation.setDuration(200);
            //滚动条开始动画
            scrollbar.startAnimation(animation);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.videoLayout:
                //点击"视频“时切换到第一页
                viewPager.setCurrentItem(0);
                break;
            case R.id.musicLayout:
                //点击“音乐”时切换的第二页
                viewPager.setCurrentItem(1);
                break;
        }
    }

    public JSONArray getJsonArray() {
        return jsonArray1;
    }
    public JSONArray getJsonArrays() {
        return jsonArray2;
    }


    public void init() {
       /* final CountDownLatch latch = new CountDownLatch(1);
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody
                .Builder()
                .add("account", "17751567370")
                .add("type", "1")
                .add("status", "0")
                .build();
        final Request request = new Request.Builder()
                .url(UrlUtil.UrlFX + "api/Myorder/list")
                .post(formBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                latch.countDown();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                //final String responseStr = response.body().string();
                //ToastUtil.showToast(PostParameterActivity.this, "Code：" + String.valueOf(response.code()));
                try {
                    String json = response.body().string();
                    JSONObject jsonObject = new JSONObject(json);
                    if (jsonObject.get("code").equals(0)) {
                        jsonArray1 = jsonObject.getJSONArray("data");
                        //System.out.println("JA"+jsonArray1.toString());
                    } else {

                        new Runnable() {

                            @Override
                            public void run() {
                                //放在UI线程弹Toast
                                Toast.makeText(MyCF.this, "网络错误", Toast.LENGTH_SHORT).show();
                            }
                        };

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        String account = null;
        try {
            Object user_info = Preferences.getParam(MyCF.this,"user_info","");
            JSONObject myJson = null;
            myJson = new JSONObject(user_info.toString());
            account = myJson.get("account").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (FX_SignInUtil.switchAccount(MyCF.this)) {
            startActivity(new Intent(MyCF.this, Login.class));
        } else {
        OKManager.getInstance().type2002(account, type, "0", new OKManager.func4() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if (jsonObject.get("code").equals(0)) {
                        jsonArray1 = jsonObject.getJSONArray("data");
                        //System.out.println("JA"+jsonArray1.toString());
                        mCardyhk = view1.findViewById(R.id.Ashdzlb);
                        mCardyhk.setLayoutManager(new LinearLayoutManager(MyCF.this));
                        mCardyhk.setAdapter(new MyCFAdapter(MyCF.this, MyCF.this));
                    } else {
                        //jsonArray1 = jsonObject.getJSONArray("data");
                        Toast.makeText(MyCF.this, jsonObject.get("message").toString(), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String string) {
                Toast.makeText(MyCF.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
        }
    }
    public void init2() {
        String account = null;
        try {
            Object user_info = Preferences.getParam(MyCF.this,"user_info","");
            JSONObject myJson = null;
            myJson = new JSONObject(user_info.toString());
            account = myJson.get("account").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (FX_SignInUtil.switchAccount(MyCF.this)) {
            startActivity(new Intent(MyCF.this, Login.class));
        } else {
            OKManager.getInstance().type2002(account, type, "1", new OKManager.func4() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        if (jsonObject.get("code").equals(0)) {
                            jsonArray2 = jsonObject.getJSONArray("data");
                            //System.out.println("JA2" + jsonArray2.toString());
                            nCardyhk = view2.findViewById(R.id.Wshdzlb);
                            nCardyhk.setLayoutManager(new LinearLayoutManager(MyCF.this));
                            nCardyhk.setAdapter(new MyCFWAdapter(MyCF.this, MyCF.this));
                        } else {
                            //jsonArray1 = jsonObject.getJSONArray("data");
                            Toast.makeText(MyCF.this, jsonObject.get("message").toString(), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String string) {
                    Toast.makeText(MyCF.this, "网络错误", Toast.LENGTH_SHORT).show();
                }
            });
        }
        }
    }
